package liantian;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Demo2 {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Sender sender = new Sender();
        new Thread(receiver).start();
        new Thread(sender).start();
    }
}


class Receiver implements Runnable{
    public void run() {
        try {
            DatagramSocket socket = new DatagramSocket(8988);
            DatagramPacket packet = new DatagramPacket(new byte[2048],2048);
            while(true){
                socket.receive(packet);
                byte[] data = packet.getData();
                int len = packet.getLength();
                String ip = packet.getAddress().getHostAddress();
                int port = packet.getPort();
                System.out.println(ip+":"+port+":"+new String(data,0,len,"UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


class Sender implements Runnable{
    public void run() {
        try {
            Scanner scanner = new Scanner(System.in);
            StringBuilder dataBuilder = new StringBuilder();
            DatagramSocket socket = new DatagramSocket();
            while (!dataBuilder.toString().equals("quit")){
                dataBuilder.replace(0, dataBuilder.toString().length(), "");
                dataBuilder.append(scanner.nextLine());
                DatagramPacket packet = new DatagramPacket(
                        dataBuilder.toString().getBytes("UTF-8"),
                        dataBuilder.toString().getBytes().length,
                        InetAddress.getByName("192.168.1.101"),
                        8888);
                socket.send(packet);
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}